<template>
  <div class="classroom-booking-container">
    <h2 class="page-title">教室借用管理</h2>

    <ClassroomMap />

    <el-card class="search-card mb-4">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <div class="search-form-items-wrapper"> <el-form-item label="教室号">
            <el-input v-model="searchForm.classroomNumber" placeholder="请输入教室号" clearable></el-input>
          </el-form-item>
          <el-form-item label="申请状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              filterable
              style="width: 220px;"
            >
              <el-option label="待审批" :value="0"></el-option>
              <el-option label="已批准" :value="1"></el-option>
              <el-option label="已拒绝" :value="2"></el-option>
              <el-option label="已撤销" :value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
            <el-button :icon="RefreshLeft" @click="resetSearch">重置</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-card>


    <el-card class="content-card">
      <div class="header-buttons mb-3">
        <el-button type="success" :icon="Plus" @click="openApplyDialog">申请教室</el-button>
      </div>

      <el-table :data="bookingList" style="width: 100%" border stripe v-loading="loading">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="classroomNumber" label="教室号" width="100"></el-table-column>
        <el-table-column prop="teacherName" label="申请人" width="100"></el-table-column>
        <el-table-column prop="purpose" label="借用目的"></el-table-column>
        <el-table-column label="开始时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column label="结束时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column label="申请状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div v-if="row.status === 0">
              <el-button type="primary" link :icon="Edit" @click="handleEdit(row)">修改</el-button>
              <el-button
                type="danger"
                link
                :icon="Delete"
                @click="handleCancel(row.id, row.teacherId)"
                >撤销</el-button
              >
            </div>
            <div v-else class="action-overlay">
              <span class="overlay-text">{{ getStatusText(row.status) }}</span>
              <el-button type="primary" link :icon="Edit" disabled>修改</el-button>
              <el-button type="danger" link :icon="Delete" disabled>撤销</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        background
        class="mt-4"
      ></el-pagination>
    </el-card>

    <el-dialog v-model="applyDialogVisible" title="申请教室" width="600px">
      <el-form
        :model="applyForm"
        :rules="applyFormRules"
        ref="applyFormRef"
        label-width="100px"
      >
        <el-form-item label="选择教室" prop="classroomId">
          <el-select v-model="applyForm.classroomId" placeholder="请选择教室" style="width: 100%;">
            <el-option
              v-for="item in allClassrooms"
              :key="item.id"
              :label="item.roomNumber"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="借用目的" prop="purpose">
          <el-input v-model="applyForm.purpose" type="textarea" :rows="3"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
              v-model="applyForm.startTime"
              type="datetime"
              placeholder="选择开始时间"
              value-format="YYYY-MM-DDTHH:mm:ss"  style="width: 100%;"
              :disabled-date="disabledDate"
              :default-time="new Date(2000, 1, 1, 9, 0, 0)"
            ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="applyForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DDTHH:mm:ss"  style="width: 100%;"
              :disabled-date="disabledDate"
              :default-time="new Date(2000, 1, 1, 9, 0, 0)"
            ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="applyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitApply">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="editDialogVisible" title="修改借用申请" width="600px">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="教室号" prop="classroomNumber">
          <el-input v-model="editForm.classroomNumber" disabled></el-input>
        </el-form-item>
        <el-form-item label="借用目的" prop="purpose">
          <el-input v-model="editForm.purpose" type="textarea" :rows="3"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="editForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
            style="width: 100%;"
            :disabled-date="disabledDate"
            :default-time="new Date(2000, 1, 1, 9, 0, 0)"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="editForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
            style="width: 100%;"
            :disabled-date="disabledDate"
            :default-time="new Date(2000, 1, 1, 17, 0, 0)"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, RefreshLeft, Plus, Edit, Delete } from '@element-plus/icons-vue';
import {
  applyBooking,
  getTeacherBookings,
  cancelBooking,
  updateBooking,
  getAllClassrooms,
} from '@/services/classroomBookingService'; // 确保路径正确
import dayjs from 'dayjs'; // 导入 dayjs
import ClassroomMap from '@/views/teacher/ClassroomMap.vue'; // 新增地图组件

// 假设当前教师ID，实际应用中应从登录信息获取
const currentTeacherId = ref(1); // 示例ID

const loading = ref(false);
const bookingList = ref([]); // 存储借用记录列表
const allClassrooms = ref([]); // 存储所有教室列表，用于申请时选择

// 搜索表单
const searchForm = reactive({
  classroomNumber: '',
  status: null,
});

// 分页数据
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

// 申请教室弹窗相关
const applyDialogVisible = ref(false);
const applyFormRef = ref(null);
const applyForm = reactive({
  teacherId: currentTeacherId.value,
  classroomId: null,
  purpose: '',
  startTime: '',
  endTime: '',
});

const applyFormRules = reactive({
  classroomId: [{ required: true, message: '请选择教室', trigger: 'change' }],
  purpose: [{ required: true, message: '请输入借用目的', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
});

// 修改教室弹窗相关
const editDialogVisible = ref(false);
const editFormRef = ref(null);
const editForm = reactive({
  id: null,
  teacherId: currentTeacherId.value,
  classroomId: null, // 用于后端更新
  classroomNumber: '', // 仅用于前端显示
  purpose: '',
  startTime: '',
  endTime: '',
});

const editFormRules = reactive({
  purpose: [{ required: true, message: '请输入借用目的', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
});

// 加载所有教室列表
const loadAllClassrooms = async () => {
  try {
    const response = await getAllClassrooms();
    if (response.status === 0 && response.data) {
      allClassrooms.value = response.data;
    } else {
      ElMessage.error(response.message || '获取教室列表失败');
    }
  } catch (error) {
    ElMessage.error('获取教室列表异常: ' + error.message);
  }
};

// 加载借用列表
const loadBookingList = async () => {
  loading.value = true;
  try {
    const params = {
      teacherId: currentTeacherId.value,
      classroomNumber: searchForm.classroomNumber || null,
      status: searchForm.status !== '' ? searchForm.status : null,
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
    };
    const response = await getTeacherBookings(params);

    if (response.status === 0 && response.data) {
      bookingList.value = response.data.records;
      pagination.total = response.data.total;
    } else {
      ElMessage.error(response.message || '获取借用记录失败');
      bookingList.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    ElMessage.error('获取借用记录异常: ' + error.message);
    bookingList.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 查询
const handleSearch = () => {
  pagination.pageNum = 1;
  loadBookingList();
};

// 重置
const resetSearch = () => {
  searchForm.classroomNumber = '';
  searchForm.status = null;
  pagination.pageNum = 1;
  loadBookingList();
};

// 打开申请教室弹窗
const openApplyDialog = () => {
  // 重置表单
  if (applyFormRef.value) {
    applyFormRef.value.resetFields();
  }
  // 确保teacherId绑定正确
  applyForm.teacherId = currentTeacherId.value;
  applyDialogVisible.value = true;
};

// 提交申请
const submitApply = async () => {
  try {
    await applyFormRef.value.validate();
    const response = await applyBooking(applyForm);
    if (response.status === 0) {
      ElMessage.success('申请提交成功，请等待审批');
      applyDialogVisible.value = false;
      loadBookingList(); // 刷新列表
    } else {
      ElMessage.error(response.message || '申请提交失败');
    }
  } catch (error) {
    if (error === false) { // Validate failed
      ElMessage.warning('请检查表单填写');
    } else {
      ElMessage.error('提交申请异常: ' + error.message);
    }
  }
};

// 处理修改
const handleEdit = (row) => {
  editForm.id = row.id;
  editForm.teacherId = row.teacherId;
  editForm.classroomId = row.classroomId; // 确保classroom_id也传递给后端
  editForm.classroomNumber = row.classroomNumber; // 仅用于显示
  editForm.purpose = row.purpose;
  
  const formatArrayToDateTime = (arr) => {
      if (!arr || arr.length < 3) return '';
      const year = arr[0] || 0;
      const month = arr[1] || 1;
      const day = arr[2] || 1;
      const hour = arr[3] || 0;
      const minute = arr[4] || 0;
      const second = arr[5] || 0;
      return dayjs(`${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}T${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`).format('YYYY-MM-DDTHH:mm:ss');
  };

  editForm.startTime = formatArrayToDateTime(row.startTime);
  editForm.endTime = formatArrayToDateTime(row.endTime);

  editDialogVisible.value = true;
};

// 提交修改
const submitEdit = async () => {
  try {
    await editFormRef.value.validate();
    // 只传后端需要的字段，时间格式为 'YYYY-MM-DDTHH:mm:ss'
    const payload = {
      id: editForm.id,
      teacherId: editForm.teacherId,
      classroomId: editForm.classroomId,
      purpose: editForm.purpose,
      startTime: dayjs(editForm.startTime).format('YYYY-MM-DDTHH:mm:ss'),
      endTime: dayjs(editForm.endTime).format('YYYY-MM-DDTHH:mm:ss')
    };
    const response = await updateBooking(payload);
    if (response.status === 0) {
      ElMessage.success('修改成功');
      editDialogVisible.value = false;
      loadBookingList(); // 刷新列表
    } else {
      ElMessage.error(response.message || '修改失败');
    }
  } catch (error) {
    if (error === false) { // Validate failed
      ElMessage.warning('请检查表单填写');
    } else {
      ElMessage.error('修改申请异常: ' + error.message);
    }
  }
};

// 撤销申请
const handleCancel = async (id, teacherId) => {
  ElMessageBox.confirm('确定要撤销这条借用申请吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const response = await cancelBooking(id, teacherId);
      if (response.status === 0) {
        ElMessage.success('撤销成功');
        loadBookingList(); // 刷新列表
      } else {
        ElMessage.error(response.message || '撤销失败');
      }
    })
    .catch(() => {
      ElMessage.info('已取消撤销');
    });
};

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  loadBookingList();
};

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.pageNum = val;
  loadBookingList();
};

// 格式化日期时间
const formatDateTime = (dateTimeArray) => {
  if (!dateTimeArray || dateTimeArray.length === 0) {
    return '';
  }
  const year = dateTimeArray[0];
  const month = dateTimeArray[1];
  const day = dateTimeArray[2];
  const hour = dateTimeArray[3] || 0;
  const minute = dateTimeArray[4] || 0;
  const second = dateTimeArray[5] || 0;

  return dayjs(`${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`).format('YYYY-MM-DD HH:mm:ss');
};

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now();
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0:
      return '待审批';
    case 1:
      return '已批准';
    case 2:
      return '已拒绝';
    case 3:
      return '已撤销';
    default:
      return '未知';
  }
};

const getStatusTagType = (status) => {
  switch (status) {
    case 0:
      return 'info';
    case 1:
      return 'success';
    case 2:
      return 'danger';
    case 3:
      return 'warning';
    default:
      return '';
  }
};

onMounted(() => {
  loadAllClassrooms(); // 页面加载时获取所有教室列表
  loadBookingList();
});
</script>

<style scoped>
/* 定义 CSS 变量，便于主题管理 */
:root {
  --primary-color: #409eff; /* Element Plus 默认蓝色 */
  --secondary-color: #67c23a; /* Element Plus 成功绿色 */
  --accent-color: #f7a23c; /* 活泼的强调色，用于标题下划线等 */
  --background-light: #f8faff; /* 浅色背景 */
  --card-background: #ffffff; /* 卡片背景色 */
  --text-dark: #303133; /* 主要文本颜色 */
  --text-light: #606266; /* 次要文本颜色 */
  --border-color: #ebeef5; /* 边框颜色 */
  --box-shadow-light: 0 4px 16px rgba(0, 0, 0, 0.05); /* 轻微的阴影 */
  --box-shadow-hover: 0 6px 20px rgba(0, 0, 0, 0.1); /* 鼠标悬停时的阴影 */
  --border-radius-base: 8px; /* 统一的圆角大小 */
  --spacing-sm: 10px; /* 小间距 */
  --spacing-md: 20px; /* 中间距 */
  --spacing-lg: 30px; /* 大间距 */
}

/* 页面整体容器样式 */
.classroom-booking-container {
  padding: var(--spacing-md);
  background-color: var(--background-light); /* 更柔和的背景色 */
  min-height: calc(100vh - 84px); /* 确保内容撑开页面高度 */
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif; /* 优化字体 */
  color: var(--text-dark); /* 使用定义好的文本颜色 */
}

/* 页面标题样式 */
.page-title {
  font-size: 2.2rem; /* 标题更大 */
  color: var(--primary-color); /* 使用主题色 */
  margin-bottom: var(--spacing-lg); /* 更多底部间距 */
  text-align: center;
  font-weight: 600; /* 更粗的字体 */
  letter-spacing: 1px; /* 增加字母间距，提升美观度 */
  position: relative; /* 用于下划线定位 */
  padding-bottom: var(--spacing-sm); /* 给下划线留出空间 */
}

/* 标题下划线强调效果 */
.page-title::after {
  content: '';
  position: absolute;
  left: 50%;
  bottom: 0;
  transform: translateX(-50%);
  width: 80px; /* 下划线宽度 */
  height: 4px; /* 下划线高度 */
  background-color: var(--accent-color); /* 强调色下划线 */
  border-radius: 2px;
}

/* 卡片样式 (搜索卡片和内容卡片) */
.search-card,
.content-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 调整搜索表单内的布局 */
.search-form-items-wrapper {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  flex-wrap: wrap; /* 允许在空间不足时换行 */
  gap: 20px; /* 控制表单项之间的间距 */
  width: 100%; /* 确保容器宽度 */
}

/* 针对 Element Plus 默认样式调整，使其更美观 */
/* 移除 el-form-item 在 flex 容器中的默认底部外边距 */
.search-form-items-wrapper .el-form-item {
  margin-bottom: 0 !important;
}


.header-buttons {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 15px;
}

.el-table {
  font-size: 14px;
  border-radius: var(--border-radius-base); /* 表格整体圆角 */
  overflow: hidden; /* 确保内容在圆角内 */
  border: 1px solid var(--border-color); /* 增加一个细边框 */
}

/* 表头背景和文字颜色 */
.el-table th.el-table__cell {
  background-color: #eef1f6; /* 浅灰色背景 */
  color: var(--text-dark);
  font-weight: 600;
}

/* 斑马纹效果 */
.el-table tr:nth-child(even) {
  background-color: #f7f9fc; /* 更柔和的斑马纹颜色 */
}

/* 鼠标悬停在行上的效果 */
.el-table tbody tr:hover > td.el-table__cell {
  background-color: #f0f6fa !important; /* 柔和的悬停背景 */
}


.el-table .el-button.el-button--text {
  padding: 0;
}

/* 状态标签样式 */
.el-tag {
  font-weight: 500;
  border-radius: 4px;
  padding: 4px 8px;
}

/* 分页组件样式 */
.el-pagination {
  justify-content: flex-end; /* 右对齐 */
  margin-top: var(--spacing-md);
  padding: var(--spacing-sm) 0;
}

/* 对话框 footer 居中 */
.el-dialog__footer {
  text-align: center;
}

/* 禁用状态操作列的样式优化 */
.action-overlay {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px; /* 按钮之间的间距 */
  width: 100%;
  height: 100%;
}

.action-overlay .el-button {
  opacity: 0.5; /* 更柔和的禁用效果 */
  cursor: not-allowed;
  pointer-events: none; /* 确保点击无效 */
}

.action-overlay .overlay-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: var(--text-light); /* 更柔和的文本颜色 */
  font-size: 13px;
  font-weight: bold;
  white-space: nowrap; /* 防止文本换行 */
  z-index: 1; /* 确保文本在按钮上方 */
  background-color: rgba(255, 255, 255, 0.8); /* 稍微透明的背景，让文本更清晰 */
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px dashed #dcdfe6; /* 虚线边框增加视觉效果 */
}

/* === 按钮样式调整开始 === */

/* 使用 :deep 穿透样式，确保悬停效果在 Element Plus 表格中生效 */
.classroom-booking-container :deep(.el-table__body tr:hover > td) {
  background-color: #e0f2f7 !important;
}

/* 修改和撤销按钮 (链接样式，使其颜色更浅) */
/* 使用 !important 确保覆盖 Element Plus 默认颜色 */
.el-table .el-button.el-button--link[type="primary"] {
  color: var(--el-color-primary-light-3) !important; /* 更浅的蓝色 */
}

.el-table .el-button.el-button--link[type="danger"] {
  color: var(--el-color-danger-light-3) !important; /* 更浅的红色 */
}

/* 申请教室按钮 (浅色一些的背景和边框) */
.header-buttons .el-button[type="success"] {
  background-color: var(--el-color-success-light-3) !important; /* 更浅的绿色 */
  border-color: var(--el-color-success-light-3) !important;
  color: #fff !important; /* 确保文字颜色仍然是白色 */
}

/* 浮动效果 for 申请教室、重置、修改、撤销 (当不禁用时) */
/* 统一设置过渡效果 */
.el-button:not(.is-disabled) {
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

/* 鼠标悬停时的浮动和阴影效果 */
.el-button:not(.is-disabled):hover {
  transform: translateY(-3px); /* 向上浮动 */
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15); /* 增加阴影，使其有“浮起来”的感觉 */
}


.el-table .el-button.el-button--link:not(.is-disabled):hover {
  transform: translateY(-2px); /* 链接按钮浮动幅度可以小一点 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); /* 链接按钮阴影更弱 */
}

/* === 按钮样式调整结束 === */
</style>